package cate.game.play;

import cate.common.table.d.GDFight;
import cate.game.fight.FightTaskContext;
import cate.game.framework.ModuleMan;
import cate.game.play.config.AllPlayCfg;
import cate.game.play.part.FightSide;
import cate.game.play.proce.play.PlayCtx;
import cate.game.play.proce.play.PlayPO;
import cate.game.role.Role;
import cate.game.util.ct.CT;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcResult;


@NoteClass("剧本模块")
public class PlayManager extends ModuleMan {
    @NoteField("剧本配置")
    public AllPlayCfg config = new AllPlayCfg();

    @Override
    public void initDependent() throws Exception {
        long t1 = System.currentTimeMillis();
        this.config.init(game.table);
        long t2 = System.currentTimeMillis();
        log.info("技能配置加载完毕,耗时{}ms", (t2 - t1));
    }

    /**
     * 由玩家主动发起的一场战斗
     * @param role
     * @param ftc
     * @param sideB
     * @return
     */
    public EcResult<PlayPO> startByRole(Role role, FightTaskContext ftc, FightSide sideB) {
        EcResult<PlayPO> r = new EcResult<>();
        EcResult<FightSide> r_side = game.fight.side.createFightSideByRole(GDFight.Team.A, role, ftc.getPositionApply(), ftc.posNum);
        if (!r_side.ok()) {
            return r.fail(r_side.message);
        }
        return startByRole(role, ftc, r_side.data, sideB);
    }

    /**
     * 由玩家主动发起的一场战斗
     * @param role
     * @param ftc
     * @param sideA 玩家阵容
     * @param sideB 敌方阵容
     * @return
     */
    public EcResult<PlayPO> startByRole(Role role, FightTaskContext ftc, FightSide sideA, FightSide sideB) {
        EcResult<PlayPO> r = start(ftc, sideA, sideB);
        if (!r.ok()) {
            return r;
        }
        game.fight.task.createFightTask(role, ftc, r.data, role.getUid());
        return r;
    }

    /**
     * 由系统发起的一场战斗
     * @param ftc
     * @param sideA
     * @param sideB
     * @return
     */
    public EcResult<PlayPO> startBySystem(FightTaskContext ftc, FightSide sideA, FightSide sideB) {
        return start(ftc, sideA, sideB);
    }

    private EcResult<PlayPO> start(FightTaskContext ftc, FightSide a, FightSide b) {
        EcResult<PlayPO> r = new EcResult<>();
        try {
            PlayCtx ctx = new PlayCtx();
            long t1 = System.currentTimeMillis();
            ctx.exe(config, ftc, a, b);
            long t2 = System.currentTimeMillis();
            r.data = ctx.po;
            if (t2 - t1 >= 50) {
                log.info("战斗计算时间={}ms,功能id={},回合数={},胜利方={},播放时间={}s",
                        t2 - t1, ftc.funcId, ctx.po.rounds.size(), ctx.po.winner, (ctx.po.endTime - ctx.po.startTime) / 1000);
            }
            return r;
        } catch (Exception e) {
            log.error("PlayManager 发生error", e);
            return r.fail("战斗过程异常");
        } finally {
            CT.gs(game).nPlayStart++;
        }
    }
}
